package com.young.cms.service.impl;

import com.young.cms.model.Column;
import com.young.cms.model.GenCol;
import com.young.cms.model.GenCreateMenuVO;
import com.young.cms.service.ICmsDBService;
import com.young.cms.service.ICmsGenColService;
import com.young.cms.util.CmsConstants;
import com.young.common.exception.BaseException;
import com.young.common.util.CollectionUtil;
import com.young.common.util.CommonUtil;
import com.young.common.util.StringUtils;
import com.young.common.core.dal.service.IDataAccessService;
import com.young.common.util.Page;
import com.young.cms.model.GenMain;
import com.young.cms.service.ICmsGenMainService;
import com.young.interfaces.log.annotation.Log;
import com.young.interfaces.ums.service.IUmsOutService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* 代码生成主体信息服务实现
* Created by rookie on 2018-04-03.
*/
@Service("genMainService")
public class CmsGenMainServiceImpl implements ICmsGenMainService {

    @Resource(name = "dataAccessService")
    IDataAccessService dataAccessService;//数据层服务

    @Resource(name="genColService")
    ICmsGenColService genColService;

    @Autowired
    IUmsOutService umsOutService;

    @Autowired
    ICmsDBService cmsDBService;

    private static final Logger logger = LoggerFactory.getLogger(CmsGenMainServiceImpl.class);

    private static final String MAPPER = CmsConstants.MAPPER.CMS_GEN_MAIN;//mapper的namespace

    //获取数据列表
    @Override
    public List<GenMain> getList(GenMain obj) {
        return dataAccessService.getList(MAPPER + ".getList", obj);
    }

    //获取数据列表(分页)
    @Override
    public List<GenMain> getPage(GenMain obj, Page page) {
        return dataAccessService.getList(MAPPER + ".getList", obj, page);
    }

    //查询单条
    @Override
    public GenMain get(String id) {
        return (GenMain)dataAccessService.getObject(MAPPER + ".get", id);
    }

    /**
     * 查询完整的代码配置(包含main和col)
     *
     * @param id
     * @return
     */
    @Override
    public GenMain getFullGen(String id) {
        GenMain genMain = this.get(id);
        if (genMain !=  null){
            //查询该配置的字段配置列表
            genMain.setColList(genColService.getListByGenId(genMain.getId()));
        }
        return genMain;
    }

    //统计数量
    @Override
    public int count(GenMain obj) {
        return (Integer)dataAccessService.getObject(MAPPER + ".count", obj);
    }

    //修改
    @Override
    public int update(GenMain obj) {
        obj.setUpdateTime(new Date());
        int i = dataAccessService.update(MAPPER + ".update", obj);
        //更新字段配置
        if (obj.getColList() != null){
            //设置字段配置所属的代码生成编号
            for(GenCol genCol : obj.getColList()){
                genCol.setGenId(obj.getId());
                genColService.update(genCol);
            }
        }
        return i;
    }

    //批量删除
    @Override
    public int delete(String[] idArr) {
        int i = 0;
        for(String id : idArr){
            i += this.delete(id);
        }
        return i;
    }

    //删除单条
    @Override
    public int delete(String id) {
        genColService.deleteByGenId(id);//删除子数据
        return dataAccessService.delete(MAPPER + ".delete", id);
    }

    //插入
    @Override
    public int insert(GenMain obj) {
        if (StringUtils.isBlank(obj.getId())){
            obj.setId(CommonUtil.getUUID());
        }
        obj.setCreateTime(new Date());
        obj.setUpdateTime(new Date());
        int i = dataAccessService.insert(MAPPER + ".insert", obj);//插入代码生成主信息
        //插入字段配置
        if (obj.getColList() != null){
            //设置字段配置所属的代码生成编号
            for(GenCol genCol : obj.getColList()){
                genCol.setGenId(obj.getId());
            }
            //批量插入字段配置
            genColService.batchInsert(obj.getColList());
        }
        return i;
    }

    //批量插入
    @Override
    public int batchInsert(List<GenMain> list) {
        int i = 0;
        for(GenMain item : list){
            i += this.insert(item);
        }
        return i;
    }

    /**
     * 快捷创建菜单
     *
     * @param createMenuVO
     */
    @Log("快捷创建菜单")
    @Override
    public void createMenu(GenCreateMenuVO createMenuVO) {
        umsOutService.createNavigate(createMenuVO.toNavigate());
    }

    /**
     * 同步字段变化
     *
     * @param genId 代码生成id
     */
    @Log("同步字段变化")
    @Override
    public void syncFieldChange(String genId) {
        // 查询代码生成信息
        GenMain genMain = this.getFullGen(genId);
        if (genMain == null) {
            throw new BaseException("查询代码生成信息失败");
        }
        // 查询表字段
        List<Column> columnList = cmsDBService.getColumsByTableName(genMain.getTableName());
        if (CollectionUtil.isEmpty(columnList)) {
            throw new BaseException("查询表字段失败");
        }
        // 转map
        Map<String, Column> columnMap = columnList.stream().collect(Collectors.toMap(Column::getField, item -> item));
        // 剔除代码生成里面已有的字段
        genMain.getColList().forEach(item -> columnMap.remove(item.getFieldName()));

        // 新字段插入默认配置
        if (CollectionUtil.isNotEmpty(columnMap)) {
            List<GenCol> newColList = columnMap.values().stream().map(GenCol::buildDefault).collect(Collectors.toList());
            newColList.forEach(item -> item.setGenId(genId));
            genColService.batchInsert(newColList);
        }
    }

}